# -*- encoding: utf-8 -*-
'''
@File    :   control.py   
@Contact :   desufnocs@163.com
@des     :   控制中心的路由
 
@Modify Time       @Author      @Version    @Desciption
------------      ----------    --------    -----------
2025/2/17 12:58   AssenImpact      1.0         None
'''
import os.path

from fastapi import APIRouter, HTTPException

from control import config as CONFIG
from ..core.Administrator import execute
from ..core.Response import success, fail
from ..core.Utils import send_base_command, device_base_info, create_script_file
from ..schemas.Control import PresetsCommandDataModel, CommandDataModel, ScriptDataModel

router = APIRouter(
    prefix="/control",
    tags=["关于指令控制的接口"],
)


@router.get(path="/computer_info", summary="获取计算机信息")
async def get_device_info():
    """
    获取设备的基本参数\n
    基本参数包括：设备ip，服务运行端口，设备名\n
    :return:
    """
    base_info = device_base_info()
    return success(msg="", data=base_info)


@router.post(path="/preset_command", summary="接受指令")
async def control(commandData: PresetsCommandDataModel):
    """
    接收预设的指令\n
    :param commandData:\n
        command:str turn_off关机 | restart 重启 | lock_on 锁定 | screen_off 息屏 \n
    :return:
    """
    command = commandData.command
    if command == "turn_off":
        completed = send_base_command("shutdown /s /t 0")
    elif command == "restart":
        completed = send_base_command("shutdown /r /t 0")
    elif command == "lock_on":
        completed = send_base_command("rundll32.exe user32.dll,LockWorkStation")
    elif command == "screen_off":
        completed = send_base_command(["powershell", "-Command",
                                       "& {(Add-Type '[DllImport(\"user32.dll\")] public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name Win32SendMessage -Namespace Win32 -PassThru)::SendMessage(-1, 0x0112, 0xF170, 2)}"])
    else:
        raise HTTPException(status_code=422, detail="数据内容不正确")

    if completed:
        return success(msg="success: 指令执行成功")
    else:
        return fail(msg="fail: 指令执行失败")


@router.post(path="/command", summary="自定义指令")
async def control(commandData: CommandDataModel):
    """
    接收自定义指令\n
    :param commandData:\n
        content:str 命令/脚本 \n
        permission:bool 是否需要管理员权限 \n
    :return:
    """
    content = commandData.content
    permission = commandData.permission
    if permission:
        msg = execute(content)
        if len(msg):
            return fail(msg=f'fail: {msg}')
    else:
        send_base_command(content)
    return success(msg="success: 指令执行成功")


@router.post(path="/script", summary="自定义脚本")
async def control(ScriptData: ScriptDataModel):
    """
    自定义脚本
    :param ScriptData:
    :return:
    """
    if not ScriptData.script_type == "vbs" and not ScriptData.script_type == "bat":
        raise HTTPException(status_code=422, detail="数据内容不正确")
    filename = ScriptData.script_id + '.' + ScriptData.script_type
    full_filename = os.path.join(CONFIG.BASE_DIR, "script", filename)
    await create_script_file(filename, ScriptData.content)
    if ScriptData.permission:
        msg = execute(full_filename)
        if len(msg):
            return fail(msg=f'fail: {msg}')
    else:
        if not send_base_command(full_filename):
            return fail(msg=f'fail: 指令执行失败')
    return success(msg="success: 指令执行成功")
